import axios from './axios';

// ==================== 搜索相关类型定义 ====================

/** 搜索建议项 */
export interface SearchSuggestionItem {
  id?: string | number;
  title?: string;
  image?: string;
  url?: string;
  type?: string;
  cy_redirect?: any;
  sub_item?: any[];
  [key: string]: any;
}

/** 搜索建议响应 */
export interface SearchSuggestionResponse {
  version: string;
  type: string;
  query: string;
  suggestions?: SearchSuggestionItem[];
}

/** 热门搜索响应 */
export interface HotSearchResponse {
  from_type: string;
  version: string;
}
// ==================== API 函数 ====================

/**
 * 获取热门搜索
 */
export const getHotSearches = async (): Promise<any[]> => {
  try {
    const res = await axios.get('/api/api/search/recommend_tag/', {
      params: {
        from_type: 'home_search',
        version: '10.6.8'
      }
    });
    
    const hotWords = res.data?.data?.hot_search_words || res.data?.data || [];
    return Array.isArray(hotWords) ? hotWords : [];
  } catch (error: any) {
    console.error('热门搜索API错误:', error);
    return [];
  }
};

/**
 * 搜索内容
 */
export const searchContent = async (keyword: string): Promise<any[]> => {
  try {
    const response = await axios.get('/api/api/v8/home_search/', {
      params: {
        query: keyword,
        version: '10.6.8'
      }
    });
    return response.data || [];
  } catch (error: any) {
    console.error('搜索API错误:', error);
    return [];
  }
};

/**
 * 获取搜索建议
 */
export const getSearchSuggestions = async (keyword: string): Promise<SearchSuggestionItem[]> => {
  try {
    const result = await axios.get("/api/api/v8/search/new_suggestion/", {
      params: {
        version: "10.6.8",
        type: "big_search",
        query: keyword
      }
    });
    
    const suggestions = result.data?.data || [];
    
    return suggestions.map((item: any, index: number) => ({
      id: index,
      title: item.item,
      type: item.type,
      image: item.type === 'image' ? item.item : undefined,
      cy_redirect: item.cy_redirect,
      sub_item: item.sub_item
    }));
  } catch (error: any) {
    console.error('搜索建议API错误:', error);
    return [];
  }
};
